package cn.ycc1.boot3mvc.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @author ycc
 * @date 2024/3/17
 */
@Slf4j
public class LogInterceptor implements HandlerInterceptor {
    private final static String MDC_TRACE_ID = "traceId";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        log.info("Interceptor Prehandle event");
        String traceIdStr = getMdcTraceId();
        MDC.put(MDC_TRACE_ID, traceIdStr);
        return true;
    }

    /**
     * 生成traceId
     * @return
     */
    private String getMdcTraceId() {
        long currentTime = System.nanoTime();
        return String.join("_", MDC_TRACE_ID, String.valueOf(currentTime));
    }
}
